package com.ufo.store.management.ui.activity;

import android.animation.ObjectAnimator;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.transition.AutoTransition;
import android.transition.ChangeBounds;
import android.transition.Fade;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.iflytek.thridparty.A;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.Isszmbalv3StockViewPagerAdapter;
import com.ufo.store.management.entity.Isszmbalv3BranchInfo;
import com.ufo.store.management.entity.Isszmbalv3SupcustInfo;
import com.ufo.store.management.entity.SerializableList;
import com.ufo.store.management.entity.SerializableMap;
import com.ufo.store.management.ui.fragment.Isszmbalv3StockListFragment;
import com.ufo.store.management.common.Config;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import android.support.design.widget.FloatingActionButton;
import com.ufo.store.management.widget.MagicIndicator.titles.ColorFlipPagerTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by taoli on 2016/12/12 0012.
 */

public class Isszmbalv3StockActivity extends BaseActivity {
    public static final String TAG = Isszmbalv3StockActivity.class.getSimpleName();
    // View name of the header image. Used for activity scene transitions
    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";
    private ImageView mReturnIv;
    private View search_v;
    private TextView mSearchTv;

    private ConstraintLayout mTitleLl;
    private MagicIndicator mMagicIndicator;
    private ConstraintLayout condition_cl;
    private ImageView styleIv;

    private TextView stockname_tv;
    private TextView stockid_tv;
    private TextView stockcost_tv;

    private ImageView stockname_iv;
    private ImageView stockid_iv;
    private ImageView stockcost_iv;

    private ViewPager mViewPager;
    private Isszmbalv3StockViewPagerAdapter mIsszmbalv3StockViewPagerAdapter;

    private List<String> mStockTypeIdList = new ArrayList<String>();
    private List<String> mStockTypeNameList = new ArrayList<String>();

    private SerializableMap mIsszmbalv3StockTypeMap  = new SerializableMap();
    private SerializableList mIsszmbalv3SupcustInfoSerializableList = new SerializableList();

    private int mMaxStockIndex = -1;
    private int mMaxStockCountByTypeId = -1;
    private String mStockTypeId = "-1";
    private String mShowStockType = "-1";

    private boolean mIsTitleLlHided = false;

    private int mMoveStartY = 0;
    private int mMoveDurY = 0;

    private FloatingActionButton mFloatingActionButton;

    private int ListStyle = 1;   // 1 : 列表   2： 网格

    private int SortMode = -1;     // 0:名字升序   1：名字降序    2：ID升序  3：ID降序    4：价格升序     5：价格降序

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        StatusBarUtil.StatusBarLightMode(this,R.color.app_bar_color,true);
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mIsszmbalv3StockTypeMap = (SerializableMap) bundle.getSerializable("Isszmbalv3StockType");
                mShowStockType = (String) bundle.getSerializable("ShowStockType");
                mIsszmbalv3SupcustInfoSerializableList = (SerializableList) bundle.getSerializable("Isszmbalv3SupcustInfo");
            }
        }

        ListStyle = Config.getIsszmbalv3StockListStyle();
    }

    private void initView() {
        setContentView(R.layout.activity_isszmbalv3_stock);

        search_v = (View)findViewById(R.id.search_v);
        mSearchTv = (TextView) findViewById(R.id.search_tv);
        mReturnIv = (ImageView) findViewById(R.id.iv_back);

        mTitleLl = (ConstraintLayout) findViewById(R.id.title_bar);
        condition_cl = (ConstraintLayout) findViewById(R.id.condition_cl);
        styleIv = (ImageView)findViewById(R.id.style_iv);

        stockname_tv = (TextView) findViewById(R.id.stockname_tv);
        stockid_tv = (TextView) findViewById(R.id.stockid_tv);
        stockcost_tv = (TextView) findViewById(R.id.stockcost_tv);

        stockname_iv = (ImageView) findViewById(R.id.stockname_iv);
        stockid_iv = (ImageView) findViewById(R.id.stockid_iv);
        stockcost_iv = (ImageView) findViewById(R.id.stockcost_iv);

        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
        search_v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSearchIsszmbalv3StockActivity();
            }
        });
        styleIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( ListStyle == 1 ){
                    ListStyle = 2;
                    styleIv.setImageResource(R.drawable.ic_grid_style_selector);
                }else if( ListStyle == 2 ){
                    ListStyle = 1;
                    styleIv.setImageResource(R.drawable.ic_list_style_selector);
                }

                Config.setIsszmbalv3StockListStyle(ListStyle);
                mIsszmbalv3StockViewPagerAdapter.setStyle(ListStyle);
            }
        });

        stockname_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                stockid_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockcost_tv.setTextColor(Color.parseColor("#5c5c5c"));
                stockname_iv.setImageResource(R.drawable.ic_triangle_press);
                stockid_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_dark);
                if( SortMode != 0 ) {
                    SortMode = 0;
                    stockname_iv.animate().rotation(180);
                }else{
                    SortMode = 1;
                    stockname_iv.animate().rotation(0);
                }
                stockid_iv.animate().rotation(0);
                stockcost_iv.animate().rotation(0);
                mIsszmbalv3StockViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });
        stockid_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockid_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                stockcost_tv.setTextColor(Color.parseColor("#5c5c5c"));
                stockname_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockid_iv.setImageResource(R.drawable.ic_triangle_press);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockname_iv.animate().rotation(0);
                if( SortMode != 2 ) {
                    SortMode = 2;
                    stockid_iv.animate().rotation(180);
                }else {
                    SortMode = 3;
                    stockid_iv.animate().rotation(0);
                }
                stockcost_iv.animate().rotation(0);
                mIsszmbalv3StockViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });
        stockcost_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockid_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockcost_tv.setTextColor(getResources().getColor(R.color.app_key_color));
                stockname_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockid_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_press);
                stockname_iv.animate().rotation(0);
                stockid_iv.animate().rotation(0);
                if( SortMode != 4 ) {
                    SortMode = 4;
                    stockcost_iv.animate().rotation(180);
                }else {
                    SortMode = 5;
                    stockcost_iv.animate().rotation(0);
                }
                mIsszmbalv3StockViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });

        if( ListStyle == 2 ){
            styleIv.setImageResource(R.drawable.ic_grid_style_selector);
        }else if( ListStyle == 1 ){
            styleIv.setImageResource(R.drawable.ic_list_style_selector);
        }
        mFloatingActionButton = (FloatingActionButton)findViewById(R.id.floating_action_bt);
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startInsertIsszmbalv3StockActivity();
            }
        });

        mViewPager = (ViewPager)findViewById(R.id.viewpager);
        mIsszmbalv3StockViewPagerAdapter = new Isszmbalv3StockViewPagerAdapter(getSupportFragmentManager());
        mIsszmbalv3StockViewPagerAdapter.setIsszmbalv3StockTypeMap(mIsszmbalv3StockTypeMap);
        mIsszmbalv3StockViewPagerAdapter.setIsszmbalv3SupcustInfoSerializableList(mIsszmbalv3SupcustInfoSerializableList);
        mIsszmbalv3StockViewPagerAdapter.setIsszmbalv3StockListStyle(ListStyle);
        mIsszmbalv3StockViewPagerAdapter.setIsszmbalv3StockListGetProcessListener(new Isszmbalv3StockListFragment.Isszmbalv3StockListGetProcessListener() {
            @Override
            public void onIsszmbalv3StockMaxIndexProcessFinish(int maxStockIndex) {
                mMaxStockIndex = maxStockIndex;
                mSearchTv.setText("搜索" + String.valueOf(mMaxStockIndex) + "件思迅商品" );
            }

            @Override
            public void onIsszmbalv3StockIndexProcessFinish(int maxStockCountByTypeId, int position) {
                if( mIsszmbalv3StockViewPagerAdapter.isFragmentVisible( position ) ){
                    mStockTypeId = mStockTypeIdList.get(position);
                    mMaxStockCountByTypeId = maxStockCountByTypeId;
                }
            }

            @Override
            public void onIsszmbalv3StockListViewTouchEvent(MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mMoveDurY = 0;
                        mMoveStartY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mMoveStartY == 0) {
                            mMoveStartY = (int) event.getY();
                        }
                        int _TempY = (int) event.getY();
                        mMoveDurY = _TempY - mMoveStartY;   //负数向上移动，正数向下移动
                        if (mMoveDurY < -Utils.dp2px(getResources(), 80) && mIsTitleLlHided == false) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = true;
                            mIsszmbalv3StockViewPagerAdapter.setTitleIsHided(true);
                            menuCollapse();
                        } else if (mMoveDurY > Utils.dp2px(getResources(), 80) && mIsTitleLlHided == true) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = false;
                            mIsszmbalv3StockViewPagerAdapter.setTitleIsHided(false);
                            menuExpand();
                        }
                        break;
                }
            }
        });

        int position = 0;
        boolean find = false;
        if ( mIsszmbalv3StockTypeMap != null && mIsszmbalv3StockTypeMap.getMap().size() > 1 ) {
            Map<String, String> map = mIsszmbalv3StockTypeMap.getMap();
            for (String key : map.keySet()) {
                mStockTypeIdList.add(key);
                mStockTypeNameList.add(map.get(key).trim());
                if( !(mShowStockType == null) ) {
                    if (!find && mShowStockType.equals(key.trim())) {
                        find = true;
                    }
                    if (!find)
                        position++;
                }
            }
        }

        mViewPager.setAdapter(mIsszmbalv3StockViewPagerAdapter);
        mViewPager.setOffscreenPageLimit(10);

        mMagicIndicator = (MagicIndicator)findViewById(R.id.id_indicator);
        initMagicIndicator(mStockTypeNameList);

        mViewPager.setCurrentItem(position);

        Transition transition1= TransitionInflater.from(this).inflateTransition(R.transition.window_enter_transition);
        transition1.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionStart(Transition transition) {

            }

            @Override
            public void onTransitionEnd(Transition transition) {
                transition.removeListener(this);
                if (mAnimatorAction != null && mAnimatorAction.isRunning()) {
                    mAnimatorAction.cancel();
                }
                mAnimatorAction = ObjectAnimator.ofFloat(mFloatingActionButton, "translationY", mFloatingActionButton.getTranslationY(),0);
                mAnimatorAction.start();
            }

            @Override
            public void onTransitionCancel(Transition transition) {

            }

            @Override
            public void onTransitionPause(Transition transition) {

            }

            @Override
            public void onTransitionResume(Transition transition) {

            }
        });
        getWindow().setEnterTransition(transition1);


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initMagicIndicator(final List<String> dataList) {
        mMagicIndicator.setBackgroundColor(Color.parseColor("#ffffff"));
        CommonNavigator commonNavigator7 = new CommonNavigator(this);
        commonNavigator7.setScrollPivotX(0.65f);
        commonNavigator7.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return dataList == null ? 0 : dataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(dataList.get(index));
                simplePagerTitleView.setNormalColor(Color.parseColor("#5c5c5c"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#2c2c2c"));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 6));
                indicator.setLineWidth(UIUtil.dip2px(context, 10));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(getResources().getColor(R.color.app_key_color));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator7);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
    }

    private android.animation.Animator mAnimatorTitle;
    private android.animation.Animator mAnimatorSv;
    private android.animation.Animator mAnimatorCondition;
    private android.animation.Animator mAnimatorContent;
    private android.animation.Animator mAnimatorAction;

    /**
     * @desc  动画隐藏标题栏，true 显示， false 隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void showHideTitleBar(boolean tag) {
        if (mAnimatorTitle != null && mAnimatorTitle.isRunning()) {
            mAnimatorTitle.cancel();
        }
        if (mAnimatorSv != null && mAnimatorSv.isRunning()) {
            mAnimatorSv.cancel();
        }
        if (mAnimatorCondition != null && mAnimatorCondition.isRunning()) {
            mAnimatorCondition.cancel();
        }
        if (mAnimatorContent != null && mAnimatorContent.isRunning()) {
            mAnimatorContent.cancel();
        }
        if (mAnimatorAction != null && mAnimatorAction.isRunning()) {
            mAnimatorAction.cancel();
        }
        if (tag) {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleLl, "translationY", mTitleLl.getTranslationY(), 0);
            mAnimatorTitle.setStartDelay(120);
            mAnimatorSv = ObjectAnimator.ofFloat(mMagicIndicator, "translationY", mMagicIndicator.getTranslationY(), getResources().getDimension(R.dimen.stock_title_height));
            mAnimatorSv.setStartDelay(80);
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_cl, "translationY", condition_cl.getTranslationY(), getResources().getDimension(R.dimen.stock_title_height) + getResources().getDimension(R.dimen.stock_type_height));
            mAnimatorCondition.setStartDelay(40);
            mAnimatorContent = ObjectAnimator.ofFloat(mViewPager, "translationY", mViewPager.getTranslationY(), getResources().getDimension(R.dimen.stock_title_height)+ getResources().getDimension(R.dimen.stock_type_height));
            mAnimatorAction = ObjectAnimator.ofFloat(mFloatingActionButton, "translationY", mFloatingActionButton.getTranslationY(),0);
        } else {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleLl, "translationY", mTitleLl.getTranslationY(), -getResources().getDimension(R.dimen.stock_title_height));
            mAnimatorSv = ObjectAnimator.ofFloat(mMagicIndicator, "translationY", mMagicIndicator.getTranslationY(), -getResources().getDimension(R.dimen.stock_type_height));
            mAnimatorSv.setStartDelay(40);
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_cl, "translationY", condition_cl.getTranslationY(), 0);
            mAnimatorCondition.setStartDelay(80);
            mAnimatorContent = ObjectAnimator.ofFloat(mViewPager, "translationY", mViewPager.getTranslationY(), 0);
            mAnimatorContent.setStartDelay(120);
            mAnimatorAction = ObjectAnimator.ofFloat(mFloatingActionButton, "translationY", mFloatingActionButton.getTranslationY(), getResources().getDimension(R.dimen.action_dis) + mFloatingActionButton.getHeight());
        }
        mAnimatorTitle.start();
        mAnimatorSv.start();
        mAnimatorCondition.start();
        mAnimatorContent.start();
        mAnimatorAction.start();
    }

    /**
     * @desc  隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void menuCollapse(){
        showHideTitleBar(false);
    }

    /**
     * @desc  显示
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void menuExpand(){
        showHideTitleBar(true);
    }

    private void startInsertIsszmbalv3StockActivity(){
        if (mMaxStockIndex > -1 && mIsszmbalv3StockTypeMap.getMap().size() > 0 && BarApplication.getInstance().mDatabaseIsSqlServer) {
            Intent toIntent = new Intent(Isszmbalv3StockActivity.this, Isszmbalv3StockEditActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("Isszmbalv3StockType", mIsszmbalv3StockTypeMap);
            bundle.putSerializable("Isszmbalv3SupcustInfo", mIsszmbalv3SupcustInfoSerializableList);
            toIntent.putExtras(bundle);
            startActivity(toIntent);
        }
    }

    private void startSearchIsszmbalv3StockActivity(){
        Intent toIntent = new Intent(Isszmbalv3StockActivity.this, SearchIsszmbalv3StockActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("Isszmbalv3StockType", mIsszmbalv3StockTypeMap);
        bundle.putSerializable("Isszmbalv3SupcustInfo", mIsszmbalv3SupcustInfoSerializableList);
        bundle.putString("StockTypeId",mStockTypeId);
        toIntent.putExtras(bundle);
        //startActivity(toIntent);
        @SuppressWarnings("unchecked")
        ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(
                Isszmbalv3StockActivity.this,
                // Now we provide a list of Pair items which contain the view we can transitioning
                // from, and the name of the view it is transitioning to, in the launched activity
                findViewById(R.id.search_tv), "searchbar");
        startActivity(toIntent, activityOptions.toBundle());
    }
}
